<?php

namespace App\Http\Controllers\H5;

use Illuminate\Http\Request;
use Laravel\Lumen\Routing\Controller;
use Tymon\JWTAuth\JWTGuard;

class QiyuController extends Controller
{
    public function auth(Request $request)
    {
        $nonce = md5(json_encode($request->json()->all()));
        $appSecret = env('QIYU_CRM_APP_SECRET');
        $time = $request->header('time', 0);
        $checksum = $request->header('checksum');
        if (sha1($appSecret . $nonce . $time) !== $checksum) {
            \Log::info(sprintf('七鱼校验不通过; app_secret: %s nonce: %s time: %s sha1: %s checksum: %s', $appSecret, $nonce, $time, sha1($appSecret . $nonce . $time), $checksum));
            return response()->json(['code' => 300, 'result' => false]);
        }

        /** @var JWTGuard $guard */
        $guard = \Auth::guard('h5')->setToken($request->token);
        $guardAuthId = 0;
        $requestUid = 0;
        try {
            $guardAuthId = (int) $guard->userOrFail()->getAuthIdentifier();
            $requestUid = (int) $request->uid;
            if ($guardAuthId !== $requestUid) {
                throw new \Exception('不匹配的用户标识');
            }
        } catch (\Throwable $e) {
            \Log::info(sprintf('%s (%s [%d]): %d %d', $e->getMessage(), $e->getFile(), $e->getLine(), $guardAuthId, $requestUid));
            return response()->json(['code' => 400, 'result' => false]);
        }

        return response()->json(['code' => 200, 'result' => true]);
    }
}
